package com.bjx.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bjx.api.system.domain.vo.UserRoleVO;
import com.bjx.system.domain.entity.UserRoleEntity;
import com.bjx.system.mapper.UserRoleMapper;
import com.bjx.system.service.IUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @desc: 用户角色关联服务实现
 * @author: liushuai
 * @date: 2022/10/17
 */
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRoleEntity> implements IUserRoleService {
    @Autowired
    private UserRoleMapper userRoleMapper;


    @Override
    public List<UserRoleVO> listUserRoleByUserId(Long userId) {
        LambdaQueryWrapper<UserRoleEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRoleEntity::getUserId, userId);
        List<UserRoleEntity> userRoleEntities = userRoleMapper.selectList(wrapper);
        List<UserRoleVO> vos = Convert.toList(UserRoleVO.class, userRoleEntities);
        return vos;
    }

    @Override
    public void saveUserRoleBatch(List<String> list, Long userId) {
        LambdaQueryWrapper<UserRoleEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRoleEntity::getUserId, userId);
        userRoleMapper.delete(wrapper);
        if (CollectionUtil.isNotEmpty(list)) {
            List<UserRoleEntity> entities = new ArrayList<>();
            list.forEach(res -> {
                UserRoleEntity entity = new UserRoleEntity();
                entity.setRoleId(Long.valueOf(res));
                entity.setUserId(userId);
                entities.add(entity);
            });
            this.saveBatch(entities);
        }

    }

}
